//
//  TestFunTabBarViewController.m
//  MKUITestApp
//  参见：https://www.jianshu.com/p/f1b0be2c9735   https://www.cnblogs.com/XYQ-208910/p/11814259.html
//  Created by 苏尚进 on 2023/7/31.
//  Copyright © 2023 moon. All rights reserved.
//

#import "TestFunTabBarViewController.h"
#import "TestElementsViewController.h"
#import "TestElementsTableViewController.h"
#import "FunTableViewController.h"
#import "TestListView.h"
#import "Menu.h"
#import "TestSafeAreaInsetsViewController.h"
#import "TestUITabBarController.h"
#import "TestMKUICustomTabBarItem.h"

@interface MKUICustomTabBarControllerParamListViewController : ListViewController<UIScrollViewDelegate>{
    CGPoint _preOffset;
}
@property(nonatomic,strong) TestScrollViewScrollHandle *scrollHandle;
@end
@implementation MKUICustomTabBarControllerParamListViewController
- (void)dealloc{
    
}
+ (MKTFuncItem *)funcItem{
    MKTFuncItem *item = [MKTFuncItem funcWithName:@"Param面板" iconImage:Menu.randomImage viewControllerClass:self];
    item.selectedIconImage =  Menu.randomImage;
    return item;
}
- (id)init{
    if(self=[super init]){
        TestMKUICustomTabBarItem *tabBarItem = [[TestMKUICustomTabBarItem alloc] init];
        tabBarItem.badgeValue = @"1";
        [tabBarItem test_setValueWithFuncItem:[self.class funcItem]];
        tabBarItem.selectedImageOfScrollToTop = [[UIImage mk_disclosureIndicatorImageWithColor:UIColor.systemBlueColor] mk_rotateImageWithRadians:M_PI_2];
        tabBarItem.imageOfScrollToTop = [[UIImage mk_disclosureIndicatorImageWithColor:[UIColor colorWithWhite:0.57 alpha:1]] mk_rotateImageWithRadians:M_PI_2];
        self.mk_customTabBarItem = tabBarItem;
    }
    return self;
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    [super traitCollectionDidChange:previousTraitCollection];
    TestMKUICustomTabBarItem *tabBarItem = self.mk_customTabBarItem;
    tabBarItem.imageOfScrollToTop = [[UIImage mk_disclosureIndicatorImageWithColor:[UIColor colorWithWhite:0.57 alpha:1]] mk_rotateImageWithRadians:M_PI_2];
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
//    if (@available(iOS 11.0, *)) {
//        NSLog(@"self safeAreaInsets:%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets));
//        NSLog(@"super.view safeAreaInsets:%@",NSStringFromUIEdgeInsets(self.view.superview.safeAreaInsets));
//    }
}
- (void)viewDidLoad{
    [super viewDidLoad];
    //监测滚动
    self.scrollHandle = [[TestScrollViewScrollHandle alloc] init];
    self.scrollHandle.position = 100;
    @MK_WEAKIFY(self);
    self.scrollHandle.whenOverPosition = ^(TestScrollViewScrollHandle *handle,BOOL isDown) {
        @MK_NORMALIZE(self);
        TestMKUICustomTabBarItem *tabBarItem = self.mk_customTabBarItem;
        TestMKUICustomTabBarItemCellViewScrollToTop *itemCell = tabBarItem.itemCell;
        [itemCell playScrollToTop:isDown animated:YES];
    };
    
    self.listView.style = MKUIListViewStyleInsetGrouped;
    self.listView.delegate = self;
    self.listView.listFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, UIScreen.mainScreen.bounds.size.height/2)];
    [self __reloadData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.scrollHandle scrollViewDidScroll:scrollView];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self __reloadData];
}
- (void)__reloadData{
    [self.listView deleteAllSections];
    [self.listView addSection];
    @MK_WEAKIFY(self);
    [self.listView addSection];
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"添加ViewController";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            NSMutableArray<UIViewController *> *viewControllers = [self.mk_customTabBarController.viewControllers mutableCopy];
            [viewControllers addObject:[MKUICustomTabBarControllerParamListViewController new]];
            [self.mk_customTabBarController setViewControllers:viewControllers animated:YES];
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"删除ViewController";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            NSMutableArray<UIViewController *> *viewControllers = [self.mk_customTabBarController.viewControllers mutableCopy];
            [viewControllers removeLastObject];
            [self.mk_customTabBarController setViewControllers:viewControllers animated:YES];
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"viewControllers顺序对调";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            NSMutableArray<UIViewController *> *viewControllers = [[NSMutableArray alloc] init];
            for(UIViewController *vc in self.mk_customTabBarController.viewControllers.reverseObjectEnumerator){
                [viewControllers addObject:vc];
            }
            [self.mk_customTabBarController setViewControllers:viewControllers animated:YES];
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"viewControllers清空";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            NSMutableArray<UIViewController *> *viewControllers = [[NSMutableArray alloc] init];
            [self.mk_customTabBarController setViewControllers:viewControllers animated:YES];
        };
        [self.listView addItem:el];
    }
    
    [self.listView addSection];
    {
        MKUIElementListViewCellSwitch *el = [[MKUIElementListViewCellSwitch alloc] init];
        el.elementView.titleText = @"设置translucent";
        el.elementView.on = self.customTabBarController.tabBar.translucent;
        el.elementView.whenChange = ^(MKUIElementViewSwitch * _Nonnull el, BOOL on) {
            @MK_NORMALIZE(self);
            self.customTabBarController.tabBar.translucent = on;
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellSelection *el = [[MKUIElementListViewCellSelection alloc] init];
        el.elementView.titleText = @"设置maxNumberOfItems";
        NSMutableArray<MKUIElementSelectOption *> *options = [[NSMutableArray alloc] init];
        for(int i=1;i<10;i++){
            [options addObject:[MKUIElementSelectOption optionWithValue:@(i) text:@(i).stringValue]];
        }
        el.elementView.options = options;
        el.elementView.selectedValue = @(self.customTabBarController.tabBar.maxNumberOfItems);
        el.elementView.whenDone = ^(__kindof MKUIElementViewSelection * _Nonnull el) {
            @MK_NORMALIZE(self);
            self.customTabBarController.tabBar.maxNumberOfItems = [(NSNumber *)el.selectedValue unsignedIntegerValue];
        };
        [self.listView addItem:el];
    }
    
    [self.listView addSection];
    {
        MKUIElementListViewCellSwitch *el = [[MKUIElementListViewCellSwitch alloc] init];
        el.elementView.titleText = @"设置tabBar.backgroundImage";
        el.elementView.on = self.customTabBarController.tabBar.backgroundImage!=nil;
        el.elementView.whenChange = ^(MKUIElementViewSwitch * _Nonnull el, BOOL on) {
            @MK_NORMALIZE(self);
            self.customTabBarController.tabBar.backgroundImage = on?[UIImage mk_imageWithUIColor:UIColor.mk_listViewGroupBackgroundColor size:CGSizeMake(1, 1)]:nil;
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellSwitch *el = [[MKUIElementListViewCellSwitch alloc] init];
        el.elementView.titleText = @"设置tabBar.hidden";
        el.elementView.on = self.customTabBarController.tabBar.hidden;
        el.elementView.whenChange = ^(MKUIElementViewSwitch * _Nonnull el, BOOL on) {
            @MK_NORMALIZE(self);
            self.customTabBarController.tabBar.hidden = on;
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"设置tabBarItemHeight";
        el.elementView.detailText = @(self.customTabBarController.tabBar.itemHeight).stringValue;
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIElementListViewCellDetail * _Nonnull el) {
            @MK_NORMALIZE(self);
            self.customTabBarController.tabBar.itemHeight = self.customTabBarController.tabBar.itemHeight==48?68:48;
            el.elementView.detailText = @(self.customTabBarController.tabBar.itemHeight).stringValue;
        };
        [self.listView addItem:el];
    }
    
    
    [self.listView addSection];
    {
        MKUIElementListViewCellSwitch *el = [[MKUIElementListViewCellSwitch alloc] init];
        el.elementView.titleText = @"显示badgeValue";
        el.elementView.on = self.mk_customTabBarItem.badgeValue.length!=0;
        if (@available(iOS 10.0, *)) {
            self.mk_customTabBarItem.badgeColor = UIColor.systemBlueColor;
        }
        el.elementView.whenChange = ^(MKUIElementViewSwitch * _Nonnull el, BOOL on) {
            @MK_NORMALIZE(self);
            self.mk_customTabBarItem.badgeValue = on?@"+99999":nil;
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"badgeValue++";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            if(self.mk_customTabBarItem.badgeValue.length==0) self.mk_customTabBarItem.badgeValue = @"1";
            else self.mk_customTabBarItem.badgeValue = @(self.mk_customTabBarItem.badgeValue.integerValue+1).stringValue;
        };
        [self.listView addItem:el];
    }
    
    [self.listView addSection];
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"self.view.safeAreaInsets";
        if (@available(iOS 11.0, *)) {
            el.elementView.subTitleText = [NSString stringWithFormat:@"self:%@,superView:%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets),NSStringFromUIEdgeInsets(self.view.superview.safeAreaInsets)];
        }
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIElementListViewCellDetail * _Nonnull el) {
            @MK_NORMALIZE(self);
            if (@available(iOS 11.0, *)) {
                el.elementView.subTitleText = [NSString stringWithFormat:@"self:%@,superView:%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets),NSStringFromUIEdgeInsets(self.view.superview.safeAreaInsets)];
            }
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"延迟打开新页面";
        el.elementView.subTitleText = @"延迟5秒打开新页面";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIViewController *vc = [[MKUICustomTabBarControllerParamListViewController alloc] init];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            });
        };
        [self.listView addItem:el];
    }
    {
        MKUIElementListViewCellDetail *el = [[MKUIElementListViewCellDetail alloc] init];
        el.elementView.titleText = @"打开新页面";
        el.elementView.subTitleText = @"使用self.mk_navigationControllerOfFirst打开，应该可以打开";
        el.elementView.accessView = el.elementView.disclosureIndicatorAccessView;
        el.whenClick = ^(__kindof MKUIListSelectionCellViewBase * _Nonnull el) {
            @MK_NORMALIZE(self);
            UIViewController *vc = [[MKUICustomTabBarControllerParamListViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            [self.mk_navigationControllerOfFirst pushViewController:vc animated:YES];
        };
        [self.listView addItem:el];
    }
    
    [self.listView reloadData];
}
- (TestFunTabBarViewController *)customTabBarController{
    if(![self.mk_customTabBarController isKindOfClass:TestFunTabBarViewController.class])return nil;
    return (TestFunTabBarViewController *)self.mk_customTabBarController;
}
- (void)viewSafeAreaInsetsDidChange{
    [super viewSafeAreaInsetsDidChange];
    UIEdgeInsets safeinsets = self.view.safeAreaInsets;
    NSLog(@"safeinsets:%@",NSStringFromUIEdgeInsets(safeinsets));
}
- (BOOL)hidesBottomBarWhenPushed{
    return [super hidesBottomBarWhenPushed];
}
@end


@interface TestFunTabBarViewController ()
@property(nonatomic,strong) UIViewController *blankViewController;
@end

@implementation TestFunTabBarViewController
+ (MKTFuncItem *)funcItem{
    return [MKTFuncItem funcWithName:@"自定义UITabBarController" viewControllerClass:self];
}
- (id)init{
    if(self=[super init]){
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBar.collectionView.clipsToBounds = NO;
    NSMutableArray<UIViewController *> *viewControllers = [[NSMutableArray alloc] init];
    {
        UIViewController *vc = [[MKUICustomTabBarControllerParamListViewController alloc] init];
        [viewControllers addObject:vc];
    }
    {
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[MKUICustomTabBarControllerParamListViewController new]];
        nav.mk_customTabBarItem.title = @"嵌套Nav";
        nav.mk_customTabBarItem.badgeValue = @"1";
        nav.mk_customTabBarItem.image = Menu.randomImage;
        nav.mk_customTabBarItem.badgeStyle = MKUICustomTabBarItemBadgeStyleDot;
        [viewControllers addObject:nav];
    }
    {
        UIViewController *vc = [[UIViewController alloc] init];
        vc.mk_customTabBarItem.itemCellClass = MKUICustomTabBarItemCellViewTestBigIcon.class;
        vc.mk_customTabBarItem.image = Menu.randomImage;
        [viewControllers addObject:vc];
        self.blankViewController = vc;
    }
    {
        UIViewController *vc = [[FunTableViewController alloc] init];
        vc.mk_customTabBarItem.itemCellClass = MKUICustomTabBarItemCellViewTestBigIcon.class;
        vc.mk_customTabBarItem.image = Menu.randomImage;
        [viewControllers addObject:vc];
    }
    {
        UIViewController *vc = [[TestUITabBarController alloc] init];
        [viewControllers addObject:vc];
    }
    {
        UIViewController *vc = [[UIViewController alloc] init];
        vc.view.backgroundColor = UIColor.redColor;
        [viewControllers addObject:vc];
    }
    self.viewControllers = viewControllers;
    self.selectedIndex = 1;
    self.delegate = self;
    [self _configNavigationForViewController:self.selectedViewController];

}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    if (@available(iOS 11.0, *)) {
//        NSLog(@"TestFunTabBarViewController safeAreaInsets:%@",NSStringFromUIEdgeInsets(self.view.safeAreaInsets));
    }
}

- (void)_configNavigationForViewController:(UIViewController *)viewController{
    self.title = viewController.title;
    self.navigationItem.rightBarButtonItems = viewController.navigationItem.rightBarButtonItems;
    self.navigationItem.leftBarButtonItems = viewController.navigationItem.leftBarButtonItems;
}
#pragma mark -delegate:MKUICustomTabBarControllerDelegate
- (void)customTabBarController:(MKUICustomTabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    [self _configNavigationForViewController:viewController];
}
- (BOOL)customTabBarController:(MKUICustomTabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if(viewController==self.blankViewController){//点击了特殊的空白名称，此时不进行选中，弹一个提示窗
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"点击空白视图" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return NO;
    }
    if(tabBarController.selectedViewController==viewController){//再次点击选中的vc
        NSArray<UIScrollView *> *scrollViews = [viewController.view mk_subviewsWithClass:UIScrollView.class resursion:YES];
        for(UIScrollView *scrollView in scrollViews){
            [scrollView mk_scrollToTopWithAnimated:YES];
        }
    }
    return YES;
}
@end

#import "UIView+Test.h"
@implementation MKUICustomTabBarItemCellViewTestBigIcon
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.bigIconImageView = [[UIImageView alloc] init];
        self.bigIconImageView.clipsToBounds = YES;
        self.bigIconImageView.layer.borderWidth = 5;
        self.bigIconImageView.layer.borderColor = UIColor.mk_listViewGroupBackgroundColor.CGColor;
        [self.contentView addSubview:self.bigIconImageView];
    }
    return self;
}
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection{
    [super traitCollectionDidChange:previousTraitCollection];
    self.bigIconImageView.layer.borderColor = UIColor.mk_listViewGroupBackgroundColor.CGColor;
}
- (void)customLayoutSubviews{
    [super customLayoutSubviews];
    CGRect bounds = self.contentView.bounds;
    CGRect f1 = bounds;
    f1.size = CGSizeMake(50, 50);
    CGRect imageFrame = [self.itemButton.imageView convertRect:self.itemButton.imageView.mk_frameOfImageContent toView:self.contentView];
    MKCGRectAlignMidXToRect(&f1, imageFrame);
    MKCGRectAlignMidYToRect(&f1, imageFrame);
    self.bigIconImageView.frame = f1;
    self.bigIconImageView.layer.cornerRadius = f1.size.width/2.0;
}
- (void)customReloadCellModel{
    [super customReloadCellModel];
    BOOL selected = self.collectionCellModel.selected;
    self.bigIconImageView.image = self.customTabBarItem.selectedImage;
    self.bigIconImageView.hidden = !selected;
    self.itemButton.hidden = selected;
    if(selected && [self.customTabBarItem mk_boolForKeyPath:@"didSelect" otherwise:NO]){//播放选中动画
        self.customTabBarItem[@"didSelect"] = nil;
        [self.bigIconImageView test_playShakingAnimating];
    }
}
- (void)collectionView:(UICollectionView *)collectionView didSelectCell:(BOOL)selected{
    if(selected){
        self.customTabBarItem[@"didSelect"] = @(YES);
    }
}
@end
